<?php

namespace Frieza\Modules\Shortlink\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\pockets\excel\DownExcel;
use Biz\tools\Mail;
use Doraemon\cache\ShortLink\ShortLinkCounter;
use Doraemon\model\ShortLink\ShortLink as mShortLink;
use Doraemon\model\ShortLink\ShortLinkReason as mShortLinkReason;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class IndexController extends Controller
{
    const PAGE_SIZE = 20;
    const SHORT_PREFIX = 'http://l.hhz1.cn/';

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $params = $request->all();
        $first = 0;
        $second = 0;
        $third = 0;
        $firstList = [];
        $secondList = [];
        $thirdList = [];
        $fourList = [];
        $reason = '';
        if (isset($params['address']) && strlen($params['address']) > 0) {
            $condition['address'] = mShortLink::ADDRESS[$params['address']];
        }
        if (isset($params['department']) && strlen($params['department']) > 0) {
            $condition['department'] = mShortLink::DEPARTMENT[$params['department']];
        }
        if (isset($params['reason']) && strlen($params['reason']) > 0) {
            $reason = $params['reason'];
            $condition['reason[~]'] = $params['reason'];
        } else {
            if (isset($params['first']) && $params['first']) {
                $first = $params['first'];
                $reasonIds[] = $params['first'];
                if (isset($params['second']) && $params['second']) {
                    $second = $params['second'];
                    $reasonIds[] = $params['second'];
                    if (isset($params['third']) && $params['third']) {
                        $third = $params['third'];
                        $reasonIds[] = $params['third'];
                        if (isset($params['four']) && $params['four']) {
                            $reasonIds[] = $params['four'];
                        }
                    }
                }
            }
            $reasonList = [];
            if ($reasonIds) {
                $reasonArr = mShortLinkReason::selectByWhere(['id' => $reasonIds]);
                foreach ($reasonArr as $row) {
                    $reasonList[$row['id']] = $row['cate_name'];
                }
            }
            if ($reasonList) {
                foreach ($reasonIds as $reasonId) {
                    if (isset($reasonList[$reasonId])) {
                        $tempStr = $reason ? '-' . $reasonList[$reasonId] : $reasonList[$reasonId];
                        $reason .= $tempStr;
                    }
                }
            }
            $condition['reason[~]'] = $reason;
        }
        $parentArr = mShortLinkReason::selectByWhere(['pid' => [0, $first, $second, $third]]);
        foreach ($parentArr as $row) {
            if ($row['pid'] == 0) {
                $firstList[$row['id']] = $row['cate_name'];
            } else if ($row['pid'] == $first) {
                $secondList[$row['id']] = $row['cate_name'];
            } else if ($row['pid'] == $second) {
                $thirdList[$row['id']] = $row['cate_name'];
            } else if ($row['pid'] == $third) {
                $fourList[$row['id']] = $row['cate_name'];
            }
        }
        $condition['ORDER'] = ['addtime' => 'DESC'];
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $condition['status'] = 1;
        $result = mShortLink::selectByWhere($condition);
        unset($condition['LIMIT']);
        unset($condition['ORDER']);
        $count = mShortLink::selectCount($condition);
        $list = [];
        foreach ($result as $row) {
            $scanCount = ShortLinkCounter::getcount($row['short_link']);
            $row['scan_count'] = $scanCount;
            $row['qrcode'] = self::SHORT_PREFIX . $row['short_link'];
            $list[] = $row;
        }
        $gridModel = new pGridDataModel($list, $count, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $reason, $firstList, $secondList, $thirdList, $fourList) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function (Grid\Filter $filter) use ($firstList, $secondList, $thirdList, $fourList) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function (Grid\Filter $filter) use ($firstList, $secondList, $thirdList, $fourList) {

                        $filter->equal('first', '一级')->select($firstList)->load('second', route('shortlink.reason'));
                        $filter->equal('second', '二级')->select($secondList)->load('third', route('shortlink.reason'));
                        $filter->equal('third', '三级')->select($thirdList)->load('four', route('shortlink.reason'));
                        $filter->equal('four', '四级')->select($fourList);
                        $filter->equal('reason', '原因');
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('address', '投放位置')->select(mShortLink::ADDRESS);
                        $filter->equal('department', '部门')->select(mShortLink::DEPARTMENT);
                    });
                });

                $searchUrl = 'https://metabase.haohaozhu.me/question/655?start_date=' . date('Y-m-d', strtotime("+1 month -6 day"));
                $searchUrl .= '&end_date=' . date('Y-m-d') . '&select_reason=' . $reason;
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->tools(function (Grid\Tools $tool) use ($searchUrl) {
                    $tool->append(new UserButton(UserButton::TYPE_HREF, '', '批量添加短链接', '', url('/admin/shortlink/batchCreate')));
                    $tool->append(new UserButton(UserButton::TYPE_HREF, '', '添加短链接', '', url('/admin/shortlink/create')));
                    if ($searchUrl) {
                        $html = '<div class="btn-group pull-right" style="margin-right: 10px"><a href="' . $searchUrl . '" target="_blank" class="btn btn-sm btn-success button-438808624">';
                        $html .= '<i class="fa fa-search"></i>&nbsp;&nbsp;统计页面</a></div>';
                        $tool->append($html);
                    }
                });
                $grid->column('id', 'Id')->width(20);
                $grid->column('department', '部门')->width(150);
                $grid->column('address', '投放位置')->width(110);
                $grid->column('short_link', '短连接地址')->display(function () {
                    return self::SHORT_PREFIX . $this->short_link;
                })->width(100);
                $grid->column('reason', '发布活动理由')->width(130)->setAttributes(['style' => 'word-break:break-all; word-wrap:break-all;']);
                $grid->column('long_link', '长连接地址(h5)')->width(150)->setAttributes(['style' => 'word-break:break-all; word-wrap:break-all;']);
                $grid->column('long_link_app', '长连接地址(app)')->width(150)->setAttributes(['style' => 'word-break:break-all; word-wrap:break-all;']);
                $grid->column('qrcode', '二维码')->newQrcode();
                $grid->column('scan_count', '扫码次数')->width(50);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                });
            });
        $content->row($gridList->render());
        return $content
            ->header('短链接列表')
            ->description(' ')
            ->breadcrumb(['text' => '短链接列表']);
    }

    public function create(Request $request, Content $content)
    {
        $form = new Form([]);
        $list = mShortLinkReason::selectByWhere(['pid' => 0, 'deep' => 1]);
        $firstList = [];
        foreach ($list as $row) {
            $firstList[$row['id']] = $row['cate_name'];
        }
        $form->select('department', '部门')->options(mShortLink::DEPARTMENT);
        $form->select('address', '投放位置')->options(mShortLink::ADDRESS);
        $form->text('long_link', '长连接地址(h5)')->required();
        $form->text('long_link_app', '长连接-app内链地址(可选)')->help("参考文档：https://confluence.haohaozhu.me/pages/viewpage.action?pageId=75825196");
        $form->divider('发送原因');
        $form->fieldChange('reason_type', '发送原因', $form)
            ->options([0 => '选择', '自定义'])
            ->default(0)
            ->callablePreCommon(function (Form $form) use ($firstList) {
            })->callableMap([
                0 => function (Form $form) use ($firstList) {
                    $form->select('first', '一级')->options($firstList)->load('second', route('shortlink.reason'));
                    $form->select('second', '二级')->options()->load('third', route('shortlink.reason'));
                    $form->select('third', '三级')->options();
                    $form->text('four', '四级');
                },
                1 => function (Form $form) {
                    $form->text('reason', '自定义原因')->help('请用"-"符号（短横线）分隔，例如：微信营造家-首发-陈醉-0206');
                },
            ]);
        $form->action('/admin/shortlink/save');
        $content->row(new UserButton(UserButton::TYPE_HREF, '', '添加原因分级', '', url('/admin/shortlink/cate/create')));
        $content->row($form);
        return $content->header('添加短链接')->breadcrumb(
            ['text' => '短链接列表', 'url' => url('/admin/shortlink/index')],
            ['text' => '添加短链接']);
    }

    public function batchCreate(Request $request, Content $content)
    {
        $adminEmail = Admin::user()->email;
        if (!$adminEmail) {
            return Admin::content(function (Content $content) {
                $content->header('批量添加短链接');
                $content->body('请设置管理员Email');
            });
        }
        $form = new Form([]);
        $list = mShortLinkReason::selectByWhere(['pid' => 0, 'deep' => 1]);
        $firstList = [];
        foreach ($list as $row) {
            $firstList[$row['id']] = $row['cate_name'];
        }
        $form->select('department', '部门')->options(mShortLink::DEPARTMENT);
        $form->select('address', '投放位置')->options(mShortLink::ADDRESS);
        $form->divider('发送原因');
        $form->fieldChange('reason_type', '发送原因', $form)
            ->options([0 => '选择', '自定义'])
            ->default(0)
            ->callablePreCommon(function (Form $form) use ($firstList) {
            })->callableMap([
                0 => function (Form $form) use ($firstList) {
                    $form->select('first', '一级')->options($firstList)->load('second', route('shortlink.reason'));
                    $form->select('second', '二级')->options()->load('third', route('shortlink.reason'));
                    $form->select('third', '三级')->options();
                    $form->text('four', '四级');
                },
                1 => function (Form $form) {
                    $form->text('reason', '自定义原因')->help('请用"-"符号（短横线）分隔，例如：微信营造家-首发-陈醉-0206');
                },
            ]);
        $form->divider('多条H5长链接');
        $form->textarea('long_link', 'H5长连接地址')->rows(10)->help('多条链接请换行，一行一个链接')->required();
        $form->action('/admin/shortlink/batchSave');
        $content->row(new UserButton(UserButton::TYPE_HREF, '', '添加原因分级', '', url('/admin/shortlink/cate/create')));
        $content->row($form);
        return $content->header('批量添加短链接')->breadcrumb(
            ['text' => '短链接列表', 'url' => url('/admin/shortlink/index')],
            ['text' => '批量添加短链接']);
    }

    public function delete(Request $request, $id)
    {
        $result = mShortLink::updateData(['status' => 0], ['id' => $id]);
        if ($result) {
            $info = mShortLink::getByWhere(['id' => $id]);
            $short_link = $info ? $info['short_link'] : '';
            if ($short_link) {
                ShortLinkCounter::del($short_link);
            }
            return redirect(url('/admin/shortlink/index'))->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public function createCate(Request $request, Content $content, $id = 0)
    {
        $form = new Form([]);
        $list = mShortLinkReason::selectByWhere(['pid' => 0, 'deep' => 1]);
        foreach ($list as $row) {
            $first[$row['id']] = $row['cate_name'];
        }
        $form->divider('原因分级');
        $form->select('first', '一级')->options($first)->load('second', route('shortlink.reason'));
        $form->select('second', '二级')->options()->load('third', route('shortlink.reason'));
        $form->select('third', '三级')->options();
        $form->divider('级别名称');
        $form->text('name', '级别名称')->required();
        $form->action('/admin/shortlink/cate/save');
        return $content->header('短链接原因分级')->breadcrumb(
            ['text' => '短链接列表', 'url' => url('/admin/shortlink/index')],
            ['text' => '短链接原因分级'])
            ->row($form);
    }

    public function save(Request $request, Content $content)
    {
        $params = $request->all();
        try {
            $reasonIds = [];
            $reasonType = $params['reason_type'];
            $reason = '';
            $four = '';
            if ($reasonType == 0) {
                if (isset($params['first']) && $params['first']) {
                    $reasonIds[] = $params['first'];
                    if (isset($params['second']) && $params['second']) {
                        $reasonIds[] = $params['second'];
                        if (isset($params['third']) && $params['third']) {
                            $reasonIds[] = $params['third'];
                            $four = isset($params['four']) ? $params['four'] : '';
                        }
                    }
                }
                $reasonList = [];
                if ($reasonIds) {
                    $reasonArr = mShortLinkReason::selectByWhere(['id' => $reasonIds]);
                    foreach ($reasonArr as $row) {
                        $reasonList[$row['id']] = $row['cate_name'];
                    }
                }
                if ($reasonList) {
                    foreach ($reasonIds as $reasonId) {
                        if (isset($reasonList[$reasonId])) {
                            $tempStr = $reason ? '-' . $reasonList[$reasonId] : $reasonList[$reasonId];
                            $reason .= $tempStr;
                        }
                    }
                    if ($four) {
                        $tempStr = $reason ? '-' . $four : $four;
                        $reason .= $tempStr;
                        if (isset($params['third']) && $params['third']) {
                            $info = mShortLinkReason::getByWhere(['deep' => 4, 'pid' => $params['third'], 'cate_name' => $four]);
                            if (empty($info)) {
                                mShortLinkReason::insertData(['deep' => 4, 'pid' => $params['third'], 'cate_name' => $four]);
                            }
                        }
                    }
                }
            } else {
                $reason = isset($params['reason']) ? $params['reason'] : '';
                $reasonArr = explode('-', $reason);
                if ($reasonArr) {
                    $this->addReasonCate($reasonArr);
                }
            }
            if (empty($params['long_link']) && empty($params['long_link_app'])) {
                throw new \Exception('至少输入H5长链接或则App长链接中一种链接');
            }
            if (empty($reason)) {
                throw new \Exception('请选择或则自定义原因');
            }
            $department = $params['department'];
            $department = is_null($department) ? '' : mShortLink::DEPARTMENT[$department];
            $address = $params['address'];
            $address = is_null($address) ? '' : mShortLink::ADDRESS[$address];
            $data = [
                'long_link' => $params['long_link'],
                'long_link_app' => $params['long_link_app'],
                'short_link' => '',
                'reason' => $reason,
                'department' => $department,
                'address' => $address,
                'admin_id' => Admin::user()->id,
                'addtime' => time(),
                'status' => 1,
            ];
            $id = mShortLink::insertData($data);
            if ($id) {
                mShortLink::createShortLink($id, $data['long_link'], $data['long_link_app']);
                return redirect(url('/admin/shortlink/index'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function batchSave(Request $request, Content $content)
    {
        $params = $request->all();
        try {
            $reasonIds = [];
            $reasonType = $params['reason_type'];
            $reason = '';
            $four = '';
            if ($reasonType == 0) {
                if (isset($params['first']) && $params['first']) {
                    $reasonIds[] = $params['first'];
                    if (isset($params['second']) && $params['second']) {
                        $reasonIds[] = $params['second'];
                        if (isset($params['third']) && $params['third']) {
                            $reasonIds[] = $params['third'];
                            $four = isset($params['four']) ? $params['four'] : '';
                        }
                    }
                }
                $reasonList = [];
                if ($reasonIds) {
                    $reasonArr = mShortLinkReason::selectByWhere(['id' => $reasonIds]);
                    foreach ($reasonArr as $row) {
                        $reasonList[$row['id']] = $row['cate_name'];
                    }
                }
                if ($reasonList) {
                    foreach ($reasonIds as $reasonId) {
                        if (isset($reasonList[$reasonId])) {
                            $tempStr = $reason ? '-' . $reasonList[$reasonId] : $reasonList[$reasonId];
                            $reason .= $tempStr;
                        }
                    }
                    if ($four) {
                        $tempStr = $reason ? '-' . $four : $four;
                        $reason .= $tempStr;
                        if (isset($params['third']) && $params['third']) {
                            $info = mShortLinkReason::getByWhere(['deep' => 4, 'pid' => $params['third'], 'cate_name' => $four]);
                            if (empty($info)) {
                                mShortLinkReason::insertData(['deep' => 4, 'pid' => $params['third'], 'cate_name' => $four]);
                            }
                        }
                    }
                }
            } else {
                $reason = isset($params['reason']) ? $params['reason'] : '';
                $reasonArr = explode('-', $reason);
                if ($reasonArr) {
                    $this->addReasonCate($reasonArr);
                }
            }
            if (empty($params['long_link'])) {
                throw new \Exception('必须输入H5长链接');
            }
            if (empty($reason)) {
                throw new \Exception('请选择或则自定义原因');
            }
            $department = $params['department'];
            $department = is_null($department) ? '' : mShortLink::DEPARTMENT[$department];
            $address = $params['address'];
            $address = is_null($address) ? '' : mShortLink::ADDRESS[$address];

            $longLink = $params['long_link'];
            $longLinkArr = explode("\r\n", $longLink);
            $longLinkArr = array_filter($longLinkArr);
            $data = [
                'long_link' => $params['long_link'],
                'long_link_app' => '',
                'short_link' => '',
                'reason' => $reason,
                'department' => $department,
                'address' => $address,
                'admin_id' => Admin::user()->id,
                'addtime' => time(),
                'status' => 1,
            ];
            $shortList = [];
            mShortLink::action(function () use ($longLinkArr, $data, &$shortList) {
                foreach ($longLinkArr as $link) {
                    $data['long_link'] = $link;
                    $id = mShortLink::insertData($data);
                    if ($id) {
                        $shortList[$id] = $data;
                    } else {
                        throw new \Exception('添加数据失败');
                    }
                }
            });
            if ($shortList) {
                $shortLinkArr = [];
                $shortLinkList = [];
                foreach ($shortList as $id => $row) {
                    $short_link = mShortLink::createShortLink($id, $row['long_link'], '');
                    $shortLinkList[] = ['short_link' => $short_link, 'long_link' => $row['long_link']];
                    $shortLinkArr[] = $short_link;
                }
                if ($shortLinkArr) {
                    $adminEmail = Admin::user()->email;
                    if ($adminEmail) {
                        $fileName = $this->admExportShortLink($reason, $shortLinkList);
                        $zip_file = $this->saveQrcodeZipFile($reason, $shortLinkArr, $fileName);
                        Mail::send($adminEmail, '短链接列表及二维码', $reason, $zip_file);
                    }
                }
                return redirect(url('/admin/shortlink/index'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function saveCate(Request $request, Content $content)
    {
        try {
            $params = $request->all();
            $pid = 0;
            $deep = 1;
            $first = $params['first'];
            $pid = $first ? $first : $pid;
            $deep = $first ? 2 : $deep;
            $second = $params['second'];
            $pid = $second ? $second : $pid;
            $deep = $second ? 3 : $deep;
            $third = $params['third'];
            $pid = $third ? $third : $pid;
            $deep = $third ? 4 : $deep;
            $name = $params['name'];
            $data = ['deep' => $deep, 'pid' => $pid, 'cate_name' => $name];
            $result = mShortLinkReason::insertData($data);
            if ($result) {
                return redirect(url('/admin/shortlink/cate/create'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function reason(Request $request)
    {
        $pid = $request->input('q', 0);
        $format = [];
        if ($pid) {
            $list = mShortLinkReason::selectByWhere(['pid' => $pid]);
            foreach ($list as $row) {
                $format[] = ['id' => $row['id'], 'text' => $row['cate_name']];
            }
        }
        return response()->json($format);
    }

    private function addReasonCate($reasonArr, $deep = 1, $pid = 0)
    {
        $i = $deep - 1;
        $cate_name = $reasonArr[$i];
        $info = mShortLinkReason::getByWhere(['deep' => $deep, 'pid' => $pid, 'cate_name' => $cate_name]);
        if ($info) {
            $pid = $info['id'];
        } else {
            $pid = mShortLinkReason::insertData(['deep' => $deep, 'pid' => $pid, 'cate_name' => $cate_name]);
        }
        if ($pid) {
            if ($deep < 4) {
                $deep++;
                $this->addReasonCate($reasonArr, $deep, $pid);
            }
        }
    }

    private function admExportShortLink($reason, $shortLinkList)
    {
        $header = ['短链接', 'H5链接地址'];
        $letter = range('A', 'B');
        $excelObj = new DownExcel();
        $excelObj->saveType = 1;
        $excelObj->setFileName('-' . $reason);
        $excelObj->setSheetTitle($reason);
        //设置列宽
        $widths = ['A' => 45, 'B' => 100];
        $excelObj->setWidth($widths);
        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');
        foreach ($header as $key => $value) {
            //设置字体
            $excelObj->setFrontName($letter[$key]);
            //设置加粗
            $excelObj->setFrontBold("$letter[$key]1");
            //设置大小
            $excelObj->setFrontSize($letter[$key]);
        }
        $fileName = $excelObj->create($shortLinkList, $header);
        return $fileName;
    }

    private function saveQrcodeZipFile($reason, array $shortLinkArr, $excelFile)
    {
        $tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR;
        $files = [];
        foreach ($shortLinkArr as $shortLink) {
            $url = ImgUrl::getQrcode(self::SHORT_PREFIX . $shortLink);
            $fileName = $tempDir . $shortLink . '.png';
            $this->saveQrcodePng($url, $fileName);
            $files[] = $fileName;
        }
        $zip_file = $tempDir . $reason . '-' . date('YmdHis') . '.zip';

        $zip = new \ZipArchive();
        $zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
        $zip->addFile($excelFile, basename($excelFile));
        foreach ($files as $file) {
            $zip->addFile($file, basename($file));
        }
        $zip->close();
        return $zip_file;
    }

    private function saveQrcodePng($url, $fileName)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $imageData = curl_exec($curl);
        curl_close($curl);
        $tp = fopen($fileName, "a");
        fwrite($tp, $imageData);
        fclose($tp);
    }


}
